import React, { useEffect, useState } from 'react'
import { Button, Table, message, Modal, Dropdown, Input } from 'antd';

import styles from './index.module.css'

import { editTask } from '../../utils/axiosRequest/api'
import { getAllcronExpression } from '../../utils/axiosRequest/api'

//列
import { columns } from '../../constant/taskColumn'
import PubSub from 'pubsub-js'

function UnderTask(props) {
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //表格展示数据
    const [showDataSource, setDataSource] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [load, setLoad] = useState(true);
    const [modalLoad, setModalLoad] = useState(true);
    const [cronData, setCronData] = useState([]);
    const [cronnBtn, setCronnBtn] = useState({ expression: '****' });
    const [userTaskId, setUserTaskId] = useState('')
    const [userTaskDes, setUserTaskDes] = useState('')
    const [confirmLoading, setConfirmLoading] = useState(false);

    //父控件传过来的值
    const { } = props;



    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData();
        //返回的函数相当于unmountComponentAtNode
        const token = PubSub.subscribe('delete-task-success', (msg, data) => {
            //订阅消息-刷新数据
            getAllTask();
        });
        return () => {
            PubSub.unsubscribe(token);
        }
    }, []);

    function initData() {
        //查询所有定时任务
        getAllTask();
    }

    //item点击
    function clickCron(key) {
        setCronnBtn(cronData[key.key]);
    };

    function getAllTask() {
        setLoad(true)
        const params = new Map()
        params.set('action', '3')
        editTask(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    handleData(data.data)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setLoad(false)
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
                setLoad(false)
            });
    }

    function handleData(taskList) {
        const tempData = [];
        const length = taskList.length;
        for (let i = 0; i < length; i++) {
            tempData.push({
                key: i,
                serial: i + 1,
                taskId: taskList[i].taskId,
                taskClassName: taskList[i].jobClassName,
                taskDesc: taskList[i].description,
                cronExpression: taskList[i].cronExpression,
                taskState: taskList[i],//把整个task传递
            })
        }
        //排序->降序
        tempData.sort((a, b) => b.taskId - a.taskId)
        //保存全量案件数据
        setDataSource(tempData)
    }

    function handleCronData(data) {
        const tempData = [];
        const length = data.length;
        for (let i = 0; i < length; i++) {
            tempData.push({
                key: i,
                label: data[i].description,
                expression: data[i].cronExpression,
                id: data[i].id,
            })
        }
        //保存全量案件数据
        setCronData(tempData)
    }

    function handleOk() {
        //确认创建任务
        setConfirmLoading(true)
        const params = new Map()
        params.set('taskId', userTaskId)
        params.set('action', '0')
        params.set('cronId', cronnBtn.id)
        params.set('description', userTaskDes)
        editTask(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    messageApi.open({ type: 'success', content: '创建成功' });
                    getAllTask();
                    handleCancel()//关闭对话框
                    //重置信息
                    setUserTaskId('');
                    setUserTaskDes('');
                    setCronnBtn({ expression: '****' });
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setConfirmLoading(false)
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
                setConfirmLoading(false)
            });
    };
    function handleCancel() {
        setIsModalOpen(false);
    };
    function creatTask() {
        setIsModalOpen(true);
        const params = new Map()
        getAllcronExpression(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    handleCronData(data.data)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setModalLoad(false)
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
                setModalLoad(false)
            });
    };

    function onChangeUserTaskId(val) {
        let userTaskId = val.target.value
        setUserTaskId(userTaskId);
    }

    function onChangeUserDes(val) {
        let userTaskDes = val.target.value
        setUserTaskDes(userTaskDes);
    }

    return (
        <div className={styles.root}>
            {contextHolder}
            <Table loading={load} title={() => {
                return (
                    <div className={styles.head_box}>
                        <Modal confirmLoading={confirmLoading} loading={modalLoad} width={'40vw'} title="创建任务" open={isModalOpen} okText="创建" cancelText="取消" onOk={handleOk} onCancel={handleCancel}>
                            <div className={styles.modal_box}>
                                <p>任务id: </p><Input onChange={onChangeUserTaskId} value={userTaskId} placeholder="任务ID" variant="filled" />
                                <p>任务描述: </p><Input onChange={onChangeUserDes} value={userTaskDes} placeholder="任务描述" variant="filled" />
                                <p>CRON表达式：
                                    <Dropdown menu={{ items: cronData, onClick: clickCron }} placement="bottom">
                                        <Button>{cronnBtn.expression}</Button>
                                    </Dropdown>
                                </p>
                            </div>
                        </Modal>
                        <Button onClick={creatTask} variant="outlined" color="primary" size={'middle'} >创建任务</Button>
                    </div>
                )
            }} size={'middle'}
                pagination={{ showSizeChanger: false, pageSize: '7', position: ['bottomCenter'], defaultCurrent: '1', total: showDataSource.length }}
                bordered={true} dataSource={showDataSource} columns={columns} scroll={{ x: 100 }} />

        </div>
    )
}


export default UnderTask

